<?php
include_once dirname(dirname(dirname(dirname(__FILE__)))) .'/np/np_xml2array.class.php';
class nl_file_encode_dayang extends nn_public_return
{
    private $manufacturer = 'LeoVideo';
    
    private $in_out_type = array(
        'ts' => array(
            'HD' => array(
                'PC-1080P-4Mbps' => array(
                    'name' => 'TS-PC-1080P-4Mbps',
                    'tag' => '31,',
                    'bitrate' => '4096',
                    'filetype' =>'ts',
                ),
                'Pad-1080P-2Mbps' => array(
                    'name' => 'TS-Mobile-1080P-2Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '2048',
                    'filetype' =>'ts',
                ),
            ),
            'STD' => array(
                'PC-1080P-4Mbps' => array(
                    'name' => 'TS-PC-1080P-4Mbps',
                    'tag' => '31,',
                    'bitrate' => '4096',
                    'filetype' =>'ts',
                ),
                'Pad-1080P-2Mbps' => array(
                    'name' => 'TS-Mobile-1080P-2Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '2048',
                    'filetype' =>'ts',
                ),
            ),
            '4K' => array(
                'PC-1080P-4Mbps' => array(
                    'name' => 'TS-PC-1080P-4Mbps',
                    'tag' => '31,',
                    'bitrate' => '4096',
                    'filetype' =>'ts',
                ),
                'Pad-1080P-2Mbps' => array(
                    'name' => 'TS-Mobile-1080P-2Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '2048',
                    'filetype' =>'ts',
                ),
            ),
        ),
        'mp4' => array(
            'HD' => array(
//                 'STB-32M-TS' => array(
//                     'name' => 'STB-32M-TS',
//                     'tag' => '26,',
//                     'bitrate' => '8192',
//                     'filetype' =>'ts',
//                 ),
                'PC-1080P-4Mbps' => array(
                    'name' => 'PC-1080P-4Mbps',
                    'tag' => '31,',
                    'bitrate' => '4096',
                    'filetype' =>'mp4',
                ),
                'Pad-1080P-2Mbps' => array(
                    'name' => 'Mobile-1080P-2Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '2048',
                    'filetype' =>'mp4',
                ),
            ),
            'STD' => array(
                'PC-1080P-4Mbps' => array(
                    'name' => 'PC-1080P-4Mbps',
                    'tag' => '31,',
                    'bitrate' => '4096',
                    'filetype' =>'mp4',
                ),
                'Pad-1080P-2Mbps' => array(
                    'name' => 'Mobile-1080P-2Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '2048',
                    'filetype' =>'mp4',
                ),
            ),
            '4K' => array(
//                 'STB-32M-TS' => array(
//                     'name' => 'STB-32M-TS',
//                     'tag' => '26,',
//                     'bitrate' => '8192',
//                     'filetype' =>'ts',
//                 ),
                'PC-1080P-8Mbps' => array(
                    'name' => 'PC-1080P-8Mbps',
                    'tag' => '31,',
                    'bitrate' => '8192',
                    'filetype' =>'mp4',
                ),
                'PC-1080P-4Mbps' => array(
                    'name' => 'PC-1080P-4Mbps',
                    'tag' => '27,28,29,30,',
                    'bitrate' => '4096',
                    'filetype' =>'mp4',
                ),
            ),
        )
    );
	
	/**
	 * 上报转码数据
	 */
	public function set_task()
	{
	    if(!isset($this->sp_config['clip_file_addr_input']) || strlen($this->sp_config['clip_file_addr_input']) <1)
	    {
	        return $this->_return_result_data(1,'切片文件输入为空:'.$this->sp_config['clip_file_addr_input']);
	    }
	    if(!isset($this->sp_config['clip_file_addr_output']) || strlen($this->sp_config['clip_file_addr_output']) <1)
	    {
	        return $this->_return_result_data(1,'切片文件输出为空:'.$this->sp_config['clip_file_addr_output']);
	    }
	    $ftp_in = rtrim($this->sp_config['clip_file_addr_input'],'/').'/'.ltrim($this->arr_params['nns_path'],'/');
	    $in_arr_file_name = pathinfo($ftp_in);
	    $in_file_name = $in_arr_file_name['basename'];
	    
	    $arr_file_info = pathinfo($in_file_name);
	    $in_file_dir = $in_arr_file_name['dirname'];
	    $ftp_out = rtrim($this->sp_config['clip_file_addr_output'],'/');
	    #TODO
	    
	    if(isset($this->arr_params['media_info']['nns_mode']) && strlen($this->arr_params['media_info']['nns_mode']) >0)
	    {
	        $this->arr_params['media_info']['nns_mode'] = strtoupper($this->arr_params['media_info']['nns_mode']);
	        $model = isset($this->in_out_type[$this->out_ex_type][$this->arr_params['media_info']['nns_mode']]) ? $this->in_out_type[$this->out_ex_type][$this->arr_params['media_info']['nns_mode']] : $this->in_out_type[$this->out_ex_type]['HD'];
	    }
	    else
	    {
	        $model =$this->in_out_type[$this->out_ex_type]['HD'];
	    }
	    
	    $inout_xml ='<?xml version="1.0" encoding="UTF-8"?>';
	    $inout_xml.='<AddTranscodeTaskRequest>';
	    $inout_xml.=   '<UserID>test</UserID>';
	    $inout_xml.=   '<TaskID>'.$this->arr_task['nns_id'].'</TaskID>';
	    $inout_xml.=   '<CallbackAddressInfo></CallbackAddressInfo>';
	    $inout_xml.=   '<TaskName>'.$this->arr_task['nns_id'].'</TaskName>';
	    $inout_xml.=   '<Prority>'.$this->arr_task['nns_priority'].'</Prority>';
	    $inout_xml.=   '<SourceFile>';
	    $inout_xml.=       '<FileType>2</FileType>';
	    $inout_xml.=       '<FileName>'.$in_file_name.'</FileName>';
	    $inout_xml.=       '<PathInfo>'.$in_file_dir.'</PathInfo>';
	    $inout_xml.=   '</SourceFile>';
	    foreach ($model as $key=>$val)
	    {
	        $out_path = $this->make_ftp_dir($in_file_dir,$ftp_out.'/'.$this->manufacturer.'/'.$key);
	        $inout_xml.=   '<TargetFile>';
// 	        $inout_xml.=       '<FileName>'.$in_file_name.'</FileName>';
	        $inout_xml.=       '<FileType>2</FileType>';
// 	        $inout_xml.=       '<FileName>'.$arr_file_info['filename'].'.'.$this->out_ex_type.'</FileName>';
	        $inout_xml.=       '<FileName>'.$arr_file_info['filename'].'.'.$val['filetype'].'</FileName>';
    	    $inout_xml.=       '<PathInfo>'.$ftp_out.'/'.$out_path.'</PathInfo>';
    	    $inout_xml.=       '<FormatTemplate>'.$val['name'].'</FormatTemplate>';
    	    $inout_xml.=   '</TargetFile>';
	    }
	    $inout_xml.=   '<TaskOption>';
	    $inout_xml.=       '<ForceTranscode>1</ForceTranscode>';
	    $inout_xml.=   '</TaskOption>';
	    $inout_xml.='</AddTranscodeTaskRequest>';
	    $result = $this->ex_curl($this->sp_config['clip_file_encode_api_url'].'/addTranscodeTask', $inout_xml);
	    if($result['ret'] !=0)
	    {
	        return $result;
	    }
	    $message_content = (isset($result['data_info']) && strlen($result['data_info'])>0) ? $result['data_info'] : '';
	    //解析下载的XML
	    $dom = new DOMDocument('1.0', 'utf-8');
	    $dom->loadXML($message_content);
	    $xml = $dom->saveXML();
	    $xml_arr = np_xml2array::getArrayData($xml);
	    if($xml_arr['ret'] !=1)
	    {
	        return _comm_make_return_data(1,'[解析xml失败]xml参数'.var_export($message_content,true));
	    }
	    if(isset($xml_arr['data']['children'][0]['children']) && is_array($xml_arr['data']['children'][0]['children']) && !empty($xml_arr['data']['children'][0]['children']))
	    {
	        $xml_arr = $xml_arr['data']['children'][0]['children'];
	        foreach ($xml_arr as $val)
	        {
	            if($val['name'] == 'Status' && $val['content'] == 0)
	            {
	                return _comm_make_return_data(0,'ok',$xml_arr['data']);
	            }
	        }
	    }
	    return _comm_make_return_data(1,'error',$xml_arr['data']);
	}
	
	private function make_ftp_dir($in_file_dir,$ftp_out)
	{
	    $url_arr_in = parse_url($in_file_dir);
	    $in_dir = isset($url_arr_in['path']) ? $url_arr_in['path'] : '';
	    $in_dir = trim($in_dir,'/');
	    //拆分FTP地址
	    $url_arr_out = parse_url($ftp_out);
	    $host_out = (isset($url_arr_out["host"]) && strlen($url_arr_out["host"]) > 0) ? $url_arr_out["host"] : '';
	    $user_out = (isset($url_arr_out["user"]) && strlen($url_arr_out["user"]) > 0) ? $url_arr_out["user"] : '';
	    $pass_out = (isset($url_arr_out["pass"]) && strlen($url_arr_out["pass"]) > 0) ? $url_arr_out["pass"] : '';
	    $path_out = (isset($url_arr_out["path"]) && strlen($url_arr_out["path"]) > 0) ? $url_arr_out["path"] : '';
	    $port_out = (isset($url_arr_out["port"]) && strlen($url_arr_out["port"]) > 0) ? $url_arr_out["port"] : 21;
	    $path_out = trim(trim($path_out,'/'));
	    $path_base = (strlen($path_out) >0) ? $path_out : '';
	    if(isset($arr_path_info['dirname']))
	    {
	        $arr_path_info['dirname'] = trim($arr_path_info['dirname'],'/');
	        if(strlen($arr_path_info['dirname']))
	        {
	            $path_base.='/'.$arr_path_info['dirname'];
	        }
	    }
	    $path_base = trim($path_base,'/');
	    if(strlen($in_dir) >0)
	    {
	        $path_base.="/".$in_dir;
	    }
	    $obj_ftp = new nl_ftp($host_out, $user_out, $pass_out,$port_out);
	    $obj_ftp->make_dir($path_base);
	    return $path_base;
	}
	
	
	/**
	 * 删除转码数据
	 */
	public function del_task()
	{
	    $inout_xml ='<?xml version="1.0" encoding="UTF-8"?>';
	    $inout_xml.='<DeleteTaskRequest>';
	    $inout_xml.=   '<TaskID>'.$this->arr_task['nns_id'].'</TaskID>';
	    $inout_xml.='</DeleteTaskRequest>';
	    $result = $this->ex_curl($this->sp_config['clip_file_encode_api_url'].'/deleteTask', $inout_xml);
	    if($result['ret'] !=0)
	    {
	        return $result;
	    }
	    $message_content = (isset($result['data_info']) && strlen($result['data_info'])>0) ? $result['data_info'] : '';
	    return _comm_make_return_data(0,'ok',var_export($message_content,true));
	}
	
	/**
	 * 获取转码状态
	 */
	public function get_task_state()
	{
		$inout_xml ='<?xml version="1.0" encoding="UTF-8"?>';
	    $inout_xml.='<QueryTaskProgressRequest>';
	    $inout_xml.=   '<TaskID>'.$this->arr_task['nns_id'].'</TaskID>';
	    $inout_xml.='</QueryTaskProgressRequest>';
	    $result = $this->ex_curl($this->sp_config['clip_file_encode_api_url'].'/queryTaskProgress', $inout_xml);
	    if($result['ret'] !=0)
	    {
	        return $result;
	    }
	    $message_content = (isset($result['data_info']) && strlen($result['data_info'])>0) ? $result['data_info'] : '';
	    //解析下载的XML
	    $dom = new DOMDocument('1.0', 'utf-8');
	    $dom->loadXML($message_content);
	    $xml = $dom->saveXML();
	    $xml_arr = np_xml2array::getArrayData($xml);
	    if($xml_arr['ret'] !=1)
	    {
	        return _comm_make_return_data(1,'[解析xml失败]xml参数'.var_export($message_content,true));
	    }
//var_dump($xml_arr['data']['children'][1]['children']);
	    if(isset($xml_arr['data']['children'][1]['children']) && is_array($xml_arr['data']['children'][1]['children']) && !empty($xml_arr['data']['children'][1]['children']))
	    {
	        $xml_arr = $xml_arr['data']['children'][1]['children'];
	        foreach ($xml_arr as $val)
	        {
	            if($val['name'] == 'TaskProgress')
	            {
	                $val['content'] = (isset($val['content']) && $val['content'] >=0) ? $val['content'] : 0;
	                return _comm_make_return_data(0,'ok',$val['content']);
	            }
	        }
	    }
	    return _comm_make_return_data(1,'error',-1);
	}
	
	public function import_queue_task()
	{
	    include_once dirname(dirname(dirname(__FILE__))).'/nn_logic/vod_media/vod_media.class.php';
	    $arr_op_queue = $this->arr_params['op_queue'];
	    if(strlen($arr_op_queue['nns_media_id']) <1)
	    {
	        return ;
	    }
	    $result_media = nl_vod_media::query_by_id($this->dc, $arr_op_queue['nns_media_id']);
	    if($result_media['ret'] !=0 || !isset($result_media['data_info']) || empty($result_media['data_info']) || !is_array($result_media['data_info']))
	    {
	        return $result_media;
	    }
	    $result_media = $result_media['data_info'];
	    $model =$this->in_out_type[$this->out_ex_type]['HD'];
	    
	    
	    if(isset($result_media['data_info']['nns_mode']) && strlen($result_media['data_info']['nns_mode']) >0)
	    {
	        $result_media['data_info']['nns_mode'] = strtoupper($result_media['data_info']['nns_mode']);
	        $model = isset($this->in_out_type[$this->out_ex_type][$result_media['data_info']['nns_mode']]) ? $this->in_out_type[$this->out_ex_type][$result_media['data_info']['nns_mode']] : $this->in_out_type[$this->out_ex_type]['HD'];
	    }
	    else
	    {
	        $model =$this->in_out_type[$this->out_ex_type]['HD'];
	    }
	    
	    
	    unset($result_media['nns_integer_id']);
// 	    $result_media['nns_message_id'] = '';
	    $result_media['nns_encode_flag'] = '1';
	    $result_media['nns_media_service'] = 'HTTP';

	    unset($arr_op_queue['nns_message_id']);
	    
	    $mix_op_url = (isset($arr_op_queue['nns_ex_data']) && strlen($arr_op_queue['nns_ex_data'])>0) ?  json_decode($arr_op_queue['nns_ex_data'],true) : null;
	    
	    $mix_media_url = (isset($result_media['nns_ext_info']) && strlen($result_media['nns_ext_info'])>0) ? json_decode($result_media['nns_ext_info'],true) : null;
	    
	    $arr_media_url = (!empty($mix_op_url) && is_array($mix_op_url)) ? $mix_op_url : $mix_media_url;
	    foreach ($model as $key=>$val)
	    {
	        $arr_temp_media = $result_media;
	        $arr_temp_media['nns_id'] = np_guid_rand();
	        $arr_temp_media['nns_import_id'] = $key.'_'.$arr_temp_media['nns_import_id'];
	        $result_media_exsist = nl_vod_media::query_media_exsist($this->dc, $arr_temp_media['nns_import_id'], $arr_temp_media['nns_cp_id'], $arr_temp_media['nns_import_source']);
            if($result_media_exsist['ret'] !=0)
	        {
	            return $result_media_exsist;
	        }
	        if(isset($result_media_exsist['data_info']) && is_array($result_media_exsist['data_info']) && !empty($result_media_exsist['data_info']))
	        {
	            continue;
	        }
	        $arr_file_info = pathinfo($arr_media_url['url']);
	        $file_base_dir = isset($arr_file_info['dirname']) ? $arr_file_info['dirname'] : '';
	        $file_base_name = isset($arr_file_info['filename']) ? $arr_file_info['filename'] : '';
	        if(strlen($file_base_name) <1)
	        {
	            continue;
	        }
	        $file_base_dir = trim($file_base_dir,'/');
	        $arr_media_url_temp = $arr_media_url;
	        $arr_media_url_temp['path'] = $arr_media_url_temp['url'] = $this->manufacturer.'/'.$key.'/'.$file_base_dir.'/'.$file_base_name.'.'.$val['filetype'];
	        $str_nns_ext_info = json_encode($arr_media_url_temp);
	        $arr_temp_media['nns_ext_info'] = $str_nns_ext_info;
	        $arr_temp_media['nns_name'] = $arr_temp_media['nns_name']."[{$key}]";
	        $arr_temp_media['nns_tag'] = $val['tag'];
	        $arr_temp_media['nns_kbps'] = $val['bitrate'];
	        $arr_temp_media['nns_filetype'] = $val['filetype'];
	        $arr_temp_media['nns_media_service'] = (isset($this->sp_config['media_service_type']) && strlen($this->sp_config['media_service_type'])>0) ? $this->sp_config['media_service_type'] : '';
	        nl_vod_media::add($this->dc, $arr_temp_media);
	        $arr_op_queue_temp = $arr_op_queue;
	        $arr_op_queue_temp['nns_id'] = np_guid_rand();
	        $arr_op_queue_temp['nns_name'] = $arr_op_queue_temp['nns_name']."[{$key}]";
	        $arr_op_queue_temp['nns_action'] = 'add';
	        $arr_op_queue_temp['nns_media_id'] = $arr_temp_media['nns_id'];
	        $arr_op_queue_temp['nns_status'] = '0';
	        $arr_op_queue_temp['nns_ex_data'] = $str_nns_ext_info;
	        nl_op_queue::add($this->dc,$arr_op_queue_temp);
	        
	    }
	    
	    
	}
}
